package com.icloud.cer.rest.common;

import java.io.Serializable;
import java.util.Locale;

import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;

import com.icloud.cer.rest.i18n.I18nUtil;

public class RequestContext implements Serializable {

	private static final long serialVersionUID = 5265804359885323931L;
	public static final String LOCALE_COOKIE_ATTRIBUTE_NAME = I18nUtil.class.getName() + ".LOCALE";
	
	private HttpServletRequest request;
	private ServletResponse response;

	public HttpServletRequest getRequest(){
		return request;
	}
	
	public ServletResponse getResponse(){
		return response;
	}
	
	public RequestContext(HttpServletRequest request, ServletResponse response) {
		this.request = request;
		this.response = response;
	}
	
	public HttpSession getSession(boolean b) {
		return request.getSession(b);
	}

	public Locale getLocale() {
		return resolveLocale(request);
	}
	
	private static Locale resolveLocale(HttpServletRequest request) {
		Locale locale = null;
		String lang=request.getParameter("lang");
		Cookie cookie = WebUtils.getCookie(request, LOCALE_COOKIE_ATTRIBUTE_NAME);
		if (null != cookie) {
			locale = StringUtils.parseLocaleString(cookie.getValue());
		} else if(lang!=null&& lang.length()>0){
			locale = StringUtils.parseLocaleString(lang);
		}
		if(locale==null){
			locale=Locale.getDefault();
		}
		return locale;
	}
}
